package com.sigmatrix.h5.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.sigmatrix.h5.dao.DisDealerDao;
import com.sigmatrix.h5.dto.DisDealersData;
import com.sigmatrix.h5.entity.Dealer;
import com.sigmatrix.h5.entity.DisDealer;
import com.sigmatrix.h5.enums.ResponseEnum;
import com.sigmatrix.h5.exception.DaoException;
import com.sigmatrix.h5.exception.ServiceException;
import com.sigmatrix.h5.request.Request;
import com.sigmatrix.h5.response.Response;
import com.sigmatrix.h5.service.DealerService;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.Utils;
import com.sigmatrix.h5.web.vo.DealersVo;
import com.sigmatrix.sc.jdbc.common.service.ServiceImpl;

/**
 * 
 *@ClassName: DealerServiceImpl
 *@Description: 平台经销商
 *@author MH
 *@date 2017年11月13日 下午6:44:45
 */
@Service
public class DealerServiceImpl extends ServiceImpl<Dealer, Integer> implements DealerService{

	@Override
	public Integer copyOfDis(DisDealer disDealer) {
		Dealer dealer = new Dealer();
		BeanUtils.copyProperties(disDealer, dealer);
		dealer.setId(null);
		return insertSelective(dealer);
	}
	
	/**
	 * 分销app合并分支-------------------------------------
	 */
	
	/**logger record*/
	private static final Logger LOGGER = LoggerFactory.getLogger(DealerServiceImpl.class);
	
	/**经销商数据库操作接口*/
	@Autowired
	private transient DisDealerDao dealersDao;

	/**
	 * (non-Javadoc)
	 *@Title: findById
	 *@Description: 
	 *@see com.sigmatrix.sc.distribution.app.inter.service.DisDealersService#findById(java.lang.Integer, java.lang.String)
	 *@author youjun
	 *@date 2017年6月26日 下午5:02:04
	 */
	@Override
	public DisDealersData findById(final Integer id, final String enterpriseCode) throws ServiceException {
		if(id==null || StringUtils.isBlank(enterpriseCode)) {
			throw new ServiceException("参数有误");
		}
		final DisDealersData data = new DisDealersData();
		try {
			final DisDealer dealers = dealersDao.findById(id, enterpriseCode);
			if(dealers!=null) {
				data.setDealerId(dealers.getId());
				data.setDealerCode(dealers.getCode());
				data.setDealerName(dealers.getName());
				data.setDealerModel(dealers.getAssistCode()); // 助记码
				data.setLevel(dealers.getLevel());
				data.setParentId(dealers.getParentId());
			}
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
		return data;
	}

	/**
	 * (non-Javadoc)
	 *@Title: findListByCondition
	 *@Description: 
	 *@see com.sigmatrix.sc.distribution.app.inter.service.DisDealersService#findListByCondition(com.sigmatrix.h5.web.vo.DealersVo)
	 *@author youjun
	 *@date 2017年6月26日 下午5:02:00
	 */
	@Override
	public List<DisDealersData> findListByCondition(final DealersVo dealersVo) throws ServiceException {

		validateBasicParamsThrow(dealersVo, false, false);
		final List<DisDealersData> dataList = new ArrayList<DisDealersData>();
		try {
			final DisDealer dealers = new DisDealer();
			if(dealersVo!=null) {
				BeanUtils.copyProperties(dealersVo, dealers);
			}
			final List<DisDealer> list = dealersDao.findListByCondition(dealers, dealersVo.getEnterpriseCode());
			if(!CollectionUtils.isEmpty(list)) {
				DisDealersData data = null;
				for(final DisDealer item:list) {
					data = new DisDealersData();
					BeanUtils.copyProperties(item, data);
					dataList.add(data);
				}
			}
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
		return dataList;
	}
	
	/**
	 *@Title: getAllDealersList
	 *@Description: 获得所有的经销商列表
	 *@return List<DisDealersData>
	 *@author youjun
	 *@date 2017年6月25日 下午2:25:38
	 *@return
	 * @throws ServiceException 
	 */
	@Override
	public List<DisDealersData> getAllDealersList(final String enterpriseCode) throws ServiceException {
		
		if(StringUtils.isBlank(enterpriseCode)) {
			throw new ServiceException("企业code不能为空");
		}
		final DealersVo dealersVo = new DealersVo();
		dealersVo.setEnterpriseCode(enterpriseCode);
		return findListByCondition(dealersVo);
	}
	
	/**
	 * (non-Javadoc)
	 *@Title: getDealersFromMap
	 *@Description: 
	 *@see com.sigmatrix.sc.distribution.app.inter.service.DisDealersService#getDealersFromMap(java.util.Map, java.lang.Integer, java.lang.String)
	 *@author youjun
	 *@date 2017年6月25日 下午3:23:08
	 */
	@Override
	public DisDealersData getDealersFromMap(final Map<Integer, DisDealersData> dealersMap, final Integer dealerId, 
			final String enterpriseCode) throws ServiceException {
		
		if(dealersMap==null) {
			throw new ServiceException("map不能为null");
		}
		if(dealerId==null || dealerId.intValue()==Cons.NULL_PRIMARY_KEY_VALUE) {
			return null;
		}
		if(StringUtils.isBlank(enterpriseCode)) {
			throw new ServiceException("企业code不能为空");
		}
		if(dealersMap.containsKey(dealerId)) {
			return dealersMap.get(dealerId);
		}
		final DisDealersData data = findById(dealerId, enterpriseCode);
		dealersMap.put(dealerId, data); // 放入map中
		return data;
	}


	/**(non-Javadoc)
	 *@Title: syncList
	 *@Description: 同步经销商列表
	 *@see com.sigmatrix.sc.distribution.app.inter.service.DisDealersService#syncList(com.sigmatrix.h5.web.vo.DealersVo)
	 *@author youjun
	 *@date 2017年6月27日 上午10:42:46
	 */
	@Override
	public Response syncList(final Request request) throws ServiceException {
		try {
			final Integer userDealerId = request.getUserDealerId();
			final String eseCode = request.getEnterpriseCode();
			
			List<DisDealersData> list = new ArrayList<DisDealersData>();
			//查询自己
			final DisDealersData dealersData = dealersDao.findByIdPart(userDealerId, eseCode);
			LOGGER.info(JSONObject.toJSONString(dealersData));
			if(Utils.isEmpty(dealersData)){
				return new Response(ResponseEnum.EXCEPTION,"登录用户所属经销商不存在，数据异常");
			}
			
			//查询子集
			List<DisDealersData> listTemp = dealersDao.findChildPart(userDealerId, eseCode);
			if(Utils.isNotEmpty(listTemp)){
				list = listTemp;
			}else{
				list.add(dealersData);
			}
			listTemp = null;
			
			//查询上级
			if(Utils.isNotEmpty(dealersData.getParentId())){
				final DisDealersData dealersParent = dealersDao.findByIdPart(dealersData.getParentId(), eseCode);
				if(Utils.isNotEmpty(dealersParent)){
					list.add(dealersParent);
				}
			}
			return new Response(ResponseEnum.SUCCESS, list);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
	
	
	/**
	 *@Title: validateBasicParamsThrow
	 *@Description: 验证基础参数,验证不通过抛出异常
	 *@return void
	 *@author youjun
	 *@date 2017年8月4日 下午5:31:21
	 *@param request
	 *@param isValidTerminalId
	 *@param isValidUserId
	 *@throws ServiceException
	 */
	protected void validateBasicParamsThrow(final Request request, final boolean isValidTerminalId, 
			final boolean isValidUserId) throws ServiceException {
		
		if(request==null) {
			throw new ServiceException("参数不能为空");
		}
		if(StringUtils.isBlank(request.getEnterpriseCode())) {
			throw new ServiceException("企业code不能为空");
		}
		if(isValidUserId && request.getUserId()==null) {
			throw new ServiceException("终端用户ID不能为空");
		}
	}

}
